package com.apiz.service.impl;

import com.apiz.annotation.AuthCheck;
import com.apiz.common.BaseResponse;
import com.apiz.common.ErrorCode;
import com.apiz.common.ResultUtils;
import com.apiz.common.model.entity.InterfaceInfo;
import com.apiz.common.model.entity.User;
import com.apiz.common.model.entity.UserInterfaceInfo;
import com.apiz.common.model.vo.InterfaceInfoVO;
import com.apiz.constant.UserConstant;
import com.apiz.exception.BusinessException;
import com.apiz.mapper.InterfaceInfoMapper;
import com.apiz.mapper.UserInterfaceInfoMapper;
import com.apiz.mapper.UserMapper;
import com.apiz.service.InterfaceInfoService;
import com.apiz.service.UserInterfaceInfoService;
import com.apiz.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.ehcache.core.util.CollectionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {


    @Resource
    UserMapper userMapper;

    @Resource
    InterfaceInfoMapper interfaceInfoMapper;

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    InterfaceInfoService interfaceInfoService;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {


        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Integer leftNum = userInterfaceInfo.getLeftNum();

        // 创建时，参数不能为空
        if (add) {
            if (userInterfaceInfo.getInterfaceInfoId() <= 0 || userInterfaceInfo.getUserId() <= 0){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口或用户不存在");
            }
        }
        // 有参数则校验
        if (leftNum <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "名字过长");
        }
    }

    @Override
    public boolean invokeCount(Long userId, Long interfaceId) {

        if (userId < 0 || interfaceId < 0){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"参数错误");
        }

        synchronized (this){
            UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("interfaceInfoId",interfaceId);
            updateWrapper.eq("userId",userId);
            updateWrapper.gt("leftNum",0);
            updateWrapper.setSql("leftNum = leftNum-1,totalNum = totalNum+1");
            this.update(updateWrapper);
        }

        return true;
    }

    @Override
    public Object payInterface(String interfaceName, String payAccount, int num, HttpServletRequest request) {

        if (StringUtils.isAnyBlank(interfaceName,payAccount)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (num < 0 || num > 9999){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount",payAccount);
        User payUser = userMapper.selectOne(queryWrapper);

        if (payUser == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"账户不存在");
        }

        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        if (user == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }



        QueryWrapper queryWrapperByInterface = new QueryWrapper();
        queryWrapperByInterface.eq("name",interfaceName);
        InterfaceInfo interfaceInfo = interfaceInfoMapper.selectOne(queryWrapperByInterface);

        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("interfaceInfoId",interfaceInfo.getId());
        updateWrapper.eq("userId",payUser.getId());
        updateWrapper.setSql("leftNum = leftNum +"+num);

        boolean result = this.update(updateWrapper);

        if (result){
            return true;
        }

        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        userInterfaceInfo.setUserId(payUser.getId());
        userInterfaceInfo.setInterfaceInfoId(interfaceInfo.getId());
        userInterfaceInfo.setTotalNum(0);
        userInterfaceInfo.setLeftNum(num);
        userInterfaceInfo.setStatus(0);
        save(userInterfaceInfo);

        return true;
    }


    @Override
    public BaseResponse<List<InterfaceInfoVO>> listTopInvokeInterfaceInfo() {

        List<InterfaceInfoVO> userInterfaceInfoList = userInterfaceInfoMapper.listTopInvokeInterfaceInfo(3);


        for (InterfaceInfoVO interfaceInfoVO : userInterfaceInfoList) {

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id",interfaceInfoVO.getInterfaceInfoId());
            InterfaceInfo interfaceInfo = interfaceInfoMapper.selectOne(queryWrapper);
            interfaceInfoVO.setName(interfaceInfo.getName());
        }
        return ResultUtils.success(userInterfaceInfoList);
    }

    @Override
    public void randomAllotInterfaceByUser(Long userId) {



        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("status",1);

        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);

        for (InterfaceInfo interfaceInfo : interfaceInfoList) {
            UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();

            userInterfaceInfo.setLeftNum(100);
            userInterfaceInfo.setUserId(userId);
            userInterfaceInfo.setInterfaceInfoId(interfaceInfo.getId());
            save(userInterfaceInfo);
        }
    }

}




